function new_value = logscale(old_value, type_flag);

% LOGSCALE - returns 1, 2 or 5 x 10^N
%
%    NEW = LOGSCALE(OLD, 'floor') returns the closest of 1, 2 or 5
%    x 10^N that is less than OLD.
%
%    NEW = LOGSCALE(OLD, 'ceil') returns the closest of 1, 2 or 5
%    x 10^N that is greater than OLD.

% By:   S.C. Molitor (smolitor@med.unc.edu)
% Date: February 23, 2000

% initialize output

new_value = old_value;

% validate arguments

if (nargin ~= 2)
   msgbox('Invalid number of arguments', 'LOGSCALE Error', 'warn');
   return
elseif (~isnumeric(old_value))
   msgbox('OLD must be a numeric array', 'LOGSCALE Error', 'warn');
   return
elseif (~ischar(type_flag) | isempty(type_flag))
   msgbox('TYPE must be a string', 'LOGSCALE Error', 'warn');
   return
end

% obtain indices of non-zero values
% obtain SGN(OLD) & ABS(OLD)
% decompose values to exponent & mantissa

pos_index = find(abs(new_value) > 0);
abs_value = abs(new_value(pos_index));
sgn_value = sign(new_value(pos_index));
exponent = 10.^floor(log10(abs_value));
mantissa = abs_value ./ exponent;

% replace mantissa with 1, 2 or 5
% use updated mantissa to recalculate new values

switch (type_flag)
case 'ceil'
   mantissa(find(mantissa >= 5)) = 10;
   mantissa(find((mantissa >= 2) & (mantissa < 5))) = 5;
   mantissa(find(mantissa < 2)) = 2;
case 'floor'
   mantissa(find(mantissa <= 2)) = 1;
   mantissa(find((mantissa > 2) & (mantissa <= 5))) = 2;
   mantissa(find(mantissa > 5)) = 5;
end
new_value(pos_index) = mantissa .* exponent .* sgn_value;
return
